//
//  TZSocket.m
//  OurFramework
//
//  Created by 949699582 on 2019/7/19.
//  Copyright © 2019 com.cunyin.paywaiter. All rights reserved.
//

#import "TZSocket.h"

@implementation TZSocket

// 开启socket
- (void)launchSocketWithServerIp:(char *)SERVER_IP andPort:(int)PORT{
    
    _clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    int result = connect (_clientSocket, (const struct sockaddr *) &addr, sizeof(addr));
    
    //少用大括号包裹代码
    if (result != 0) {
        NSLog(@"连接失败");
        return;
    }
}

// 关闭socket
- (void)closeSocket{
    close(_clientSocket);
}

// 发送数据
- (void)sendMessage:(const char *)sendMessage{
    ssize_t sendCount = send(_clientSocket, sendMessage, strlen(sendMessage), 0);
    NSLog(@"发送的字节数 =%zd",sendCount);
}

// 接收数据
- (void)receiveMessageWithBlock:(SocketBlock)block{
    
    uint8_t buffer[1024];
    ssize_t recvCount = recv(_clientSocket, buffer, sizeof(buffer), 0);
    NSLog(@"接收的字节数 =%zd",recvCount);
    
    // 把字节数组转换成字符串
    NSData *data = [NSData dataWithBytes:buffer length:recvCount];
    NSString *recvMsg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"收到的字符串 =%@",recvMsg);
    if (recvMsg.length > 0) {
        block(recvMsg);
    }
}

// 基本用法
- (void)socketBaseic{
    #define PORT 12345
    #define SERVER_IP "127.0.0.1"
    // 1.创建Socket
    // 第一个参数 domain 协议族 指定IPv4
    // 第二个参数 type socket的类型 流socket 数据包socket
    // 第三个参数 protocol 协议
    
    // 返回值 如果创建成功返回的事socket的描述符, 失败-1
    int clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
    // 2.建立连接
    // 第一个参数 socket的描述符
    // 第二个参数 结构体 ip地址和端口
    // 第三个参数 结构体的长度 sizeof
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    int result = connect (clientSocket, (const struct sockaddr *) &addr, sizeof(addr));
    //少用大括号包裹代码
    if (result != 0) {
        NSLog(@"失败");
        return;
    }
    
    // 3.向服务器发送数据
    // 成功则返回实际传送出去的字符数,失败返回 -1
    // 第三个参数是字符数不是字节数
    const char *msg = "hello world";
    ssize_t sendCount = send(clientSocket, msg, strlen(msg), 0);
    NSLog(@"发送的字节数 =%zd",sendCount);
    
    //    连接服务器
    //    1.打开Netcat,模拟服务器
    //    打开终端
    //    nc -lk 12345
    
    //    4.接收服务器返回的数据
    // 返回的事实际接收的字节个数
    uint8_t buffer[1024];
    ssize_t recvCount = recv(clientSocket, buffer, sizeof(buffer), 0);
    NSLog(@"接收的字节数 =%zd",recvCount);
    
    // 把字节数组转换成字符串
    NSData *data = [NSData dataWithBytes:buffer length:recvCount];
    NSString *recvMsg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"收到的字符串 =%@",recvMsg);
    
    // 5.关闭连接
    close(clientSocket);
}
@end
